package com.unytech.arl;

import android.content.Context;
import android.os.Handler;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.util.Log;
import android.util.TypedValue;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.squareup.picasso.Picasso;

import java.util.ArrayList;
import java.util.List;
/**
 * 轮播图的方法
 * 对外暴露的方法：
 * 一 让外界指定数据，此控件负责显示数据
 * public void setItems(List<RollItem>  )
 *
 * 关心三个View
 * ViewPager、TextView 、点（3件事情）
 *
 * 二 开始或停止滚动
 * public void  setAutoRoll(boolean )
 *
 * hander.postDelay  延时执行轮播
 * handle.removeCallbacks 移除回调,避免重复调用
 */
/**
 * Created by zed on 2016/10/31/0031.
 */
public class AutoRollLayout extends FrameLayout implements View.OnClickListener {
    private ViewPager mViewPager;
    private TextView mTextView;
    private LinearLayout mLinearLayout;

    public AutoRollLayout(Context context) {
        this(context, null);
    }

    public AutoRollLayout(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public AutoRollLayout(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs,defStyleAttr);
        init();//初始化数据
    }

    /**
     * 初始化数据
     */
    private void init() {
        View.inflate(getContext(), R.layout.arl_arl_layout, this);
        mViewPager = (ViewPager) findViewById(R.id.arl_arl_vp);
        mTextView = (TextView) findViewById(R.id.arl_arl_tv);
        mLinearLayout = (LinearLayout) findViewById(R.id.arl_arl_ll);
        mViewPager.setOnPageChangeListener(mPageListener);
    }
    /**
     * TODO 1 对外暴露数据,让外界指定数据
     */
    List<AutoRallItem> mItems;
    public void setItems(List<AutoRallItem> items) {
        this.mItems = items;

        mViewPager.setAdapter(mViewPagerAdapter);
        mTextView.setText(null);
        mLinearLayout.removeAllViews();
        //添加点的方法
        addDots();

        if (mItems==null){
            return;
        }
        mPageListener.onPageSelected(0);
    }
    //添加点的方法
    private void addDots() {
        if (mItems == null) {
            return;
        }

        int pxFor10Dp = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 10, getResources().getDisplayMetrics());
        for (AutoRallItem item : mItems) {
            View dot = new View(getContext());
            LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(pxFor10Dp, pxFor10Dp);
            lp.setMargins(0, 0, pxFor10Dp, 0);
            dot.setLayoutParams(lp);
            dot.setBackgroundResource(R.drawable.arl_dot_selector);

            mLinearLayout.addView(dot);
            dot.setOnClickListener(this);
        }
    }

    private PagerAdapter mViewPagerAdapter = new PagerAdapter() {
        @Override
        public int getCount() {
            return mItems == null ? 0 : mItems.size();
        }

        @Override
        public boolean isViewFromObject(View view, Object object) {
            return view == object;
        }

        List<ImageView> cache = new ArrayList<>();
        @Override
        public Object instantiateItem(ViewGroup container, int position) {
            if (cache.isEmpty()){
                ImageView imageView= new ImageView(container.getContext());
                imageView.setScaleType(ImageView.ScaleType.FIT_XY);
                cache.add(imageView);
            }

            ImageView imageView = cache.remove(0);

            Picasso.with(container.getContext()).load(mItems.get(position).getPicUrl()).into(imageView);

            container.addView(imageView);
            return imageView;
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            ImageView imageView = (ImageView) object;
            cache.add(imageView);
            container.removeView(imageView);
        }
    };
    /**
     * TODO 2 开始滚动的方法
     */
    public static Handler sHandler = new Handler();
    boolean mAutoRall;

    public void setAutoRall(boolean autoRall) {
        if (mAutoRall == autoRall) {
            return;
        }
        this.mAutoRall = autoRall;

        if (autoRall) {
            sHandler.postDelayed(goNextPageRunnable, 1000);
        } else {
            sHandler.removeCallbacks(goNextPageRunnable);
        }
    }

    //跳转到下一页的Runnable
    Runnable goNextPageRunnable = new Runnable() {
        @Override
        public void run() {
            goNextPager();//跳转到下一页的方法
            sHandler.postDelayed(this, 1000);
        }
    };

    //跳转到下一页的方法
    private boolean mFromLeftToRight = true;
    private void goNextPager() {

        if(mViewPagerAdapter.getCount() ==1){
            return;
        }

        int currentIndex = mViewPager.getCurrentItem();
        if (currentIndex == 0) {
            mFromLeftToRight = true;
        }
        if (currentIndex == mViewPagerAdapter.getCount() - 1) {
            mFromLeftToRight = false;
        }

        int targetIndex = 0;
        if (mFromLeftToRight) {
            targetIndex = currentIndex + 1;
        } else {
            targetIndex = currentIndex - 1;
        }
        mViewPager.setCurrentItem(targetIndex);
    }

    private ViewPager.OnPageChangeListener mPageListener = new ViewPager.SimpleOnPageChangeListener() {
        @Override
        public void onPageSelected(int position) {

            mTextView.setText(mItems.get(position).getTitle());

            for (int i = 0; i < mViewPagerAdapter.getCount(); i++) {
                mLinearLayout.getChildAt(i).setEnabled(i != position);
            }
        }
    };

    @Override
    public void onClick(View v) {
        int indexOfChild = mLinearLayout.indexOfChild(v);
        Log.d("atuorallLayout", "onClick: "+indexOfChild);
        mViewPager.setCurrentItem(indexOfChild);
    }
}